package cn.qzzg.common.interceptor;

import cn.qzzg.common.ResultBean;
import cn.qzzg.enums.CodeEnum;
import cn.qzzg.pojo.User;
import cn.qzzg.service.UserService;
import cn.qzzg.util.JJWTTokenUtil;
import cn.qzzg.util.RedisUtil;
import cn.qzzg.util.ResponseUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

/**
 * token拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    RedisUtil redisUtil;

    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
            return true;
        try {
            String authorization = request.getHeader("Authorization");
            if (authorization == null)
                throw new JwtException(null);
            Claims claims = JJWTTokenUtil.verifyToken(authorization);
            String userId = claims.getSubject();
            String userToken = redisUtil.getHash("user_token", userId);
            if (!authorization.equals(userToken)) {
                // 用户登录过期
                ResponseUtil.writer(request, response, ResultBean.error(CodeEnum.USER_ERROR_A0230));
                return false;
            }
            User user = userService.findById(userId);
            request.setAttribute("userId", userId);
            request.setAttribute("role", user.getRoleId());
            request.setAttribute("name", user.getName());
        } catch (JwtException jwtException) {
            // 用户令牌异常
            ResponseUtil.writer(request, response, ResultBean.error(CodeEnum.USER_ERROR_A0340));
            return false;
        } catch (Exception e) {
            // 系统错误
            ResponseUtil.writer(request, response, ResultBean.error(CodeEnum.SYSTEM_ERROR_B0001));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {

    }
}
